package common

import (
	"fmt"
	"gitee.com/yunduansing/gocommon/configs"
	myDb "gitee.com/yunduansing/gocommon/db"
	myRedis "gitee.com/yunduansing/gocommon/redis"
	redisCluster "github.com/chasex/redis-go-cluster"
	redis2 "github.com/go-redis/redis/v8"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gomodule/redigo/redis"
	"github.com/jmoiron/sqlx"
	"strings"
	"sync"
)

type ConfigModel struct {
	Redis RedisModel `yaml:"redis"`
	Port  int    `yaml:"port"`
}
type RedisModel struct {
	Default string `yaml:"default"`
}


func GetRedisDefault() (addr string,maxActive int) {
	cfg,err:=configs.GetYAMLConfig("./config.yml")
	if err!=nil{
		fmt.Println(err)
	}
	r,_:=configs.GetConfig(cfg,"redis.default.max-active")
	a,_:=configs.GetConfig(cfg,"redis.default.addr")
	return a.(string),r.(int)
}

func GetRedisClusterNodes() []string {
	cfg,err:=configs.GetYAMLConfig("./config.yml")
	if err!=nil{
		fmt.Println(err)
	}
	a,_:=configs.GetConfig(cfg,"redis.cluster")
	return strings.Split(a.(string),",")
}

var DB *sqlx.DB
var once sync.Once

func GetDB() (db *sqlx.DB,err error) {
	if DB!=nil{
		db=DB
		return
	}
	once.Do(func() {
		DB,err=myDb.CreateMySQLDefault(configs.GetDbDefault())
		db=DB
	})
	return
}

func CloseDB()  {
	if DB!=nil{
		DB.Close()
	}
}

var pool *redis.Pool
var redisOnce sync.Once

func GetRedisConn() redis.Conn {
	var err error
	redisOnce.Do(func() {
		addr,max:=GetRedisDefault()
		pool,err=myRedis.CreatePool(addr,max)
	})
	if err!=nil{
		panic(err)
	}
	return pool.Get()
}
var cluster *redisCluster.Cluster
var clusterOnce sync.Once
func GetRedisCluster() (c *redisCluster.Cluster,err error) {
	clusterOnce.Do(func() {
		cluster,err=myRedis.CreateCluster(GetRedisClusterNodes())
	})
	return cluster,err
}
var newCluster *redis2.ClusterClient
var newClusterOnce sync.Once
func NewCluster() (c *redis2.ClusterClient) {
	newClusterOnce.Do(func() {
		newCluster=redis2.NewClusterClient(&redis2.ClusterOptions{
			Addrs:              GetRedisClusterNodes(),
			MinIdleConns:       1000,
			MaxConnAge:         5000,
		})
	})
	return newCluster
}
